#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "misc.h"

int main(int argc, char **argv){
	int size = 0, i = 0, a = 0, hsize = 0, foundFlag = 0;
	char *name = NULL, *pswd = NULL, *cryptPswd = NULL;
	char buffer[100] = {0}, hexBuffer[160] = {0}, SaltyPswd[120] = {0};
	BasicHashFunctionPtr h = NULL;
	record *r = NULL;

	/*check the no. of param. the user entered*/
	if (argc != 2) {
		fprintf(stderr, "Error: Usage authenticate <authentication table text file>\n");
		return 0;
	}
	a = createfArr(argv[1], &r, &h, &size,&hsize, 1);
	if (a == 0){
		fprintf(stderr, "error with file: %s\n", argv[1]);
		return 0;
	}
	else if (h == NULL){
		fprintf(stderr, "unknown hash function in: %s\n", argv[1]);
		freefArr(&r, size, 1);
		return 0;
	}
	else if (a == -7){
		fprintf(stderr, "error allocating mem. to process the file: %s\n", argv[1]);
		freefArr(&r, size, 1);
		return 0;
	}
	cryptPswd = (char *)calloc(hsize+1, sizeof(char));
	if (cryptPswd == NULL){
		fprintf(stderr, "error allocating mem. \n");
		freefArr(&r, size, 1);
		return 0;
	}
	cryptPswd[hsize] = '\0';

	while (1){
		printf(">>");
		readBuffer(buffer);
		if (strcmp(buffer,"quit") == 0) break;
		else if (*buffer == '\0')
			continue;
		else if (checkBuffer(buffer) == 0) {
			fprintf(stderr, "Error: Commands are either quit or <user name>tab<password>.\n");
			continue;
		}

		name = buffer;
		pswd = buffer;
		while (*pswd != '\t'){
			pswd++;
		}
		*pswd = '\0';
		pswd++;
		foundFlag = 0;
		for (i = 0; i < size; i++){
			if (strcmp(r[i].name, name) == 0){
				strcpy(SaltyPswd, pswd);
				strcat(SaltyPswd, r[i].salt);
				cryptHash (h, SaltyPswd, (unsigned char *)cryptPswd);
				binary2hexa((unsigned char *)cryptPswd, hsize, hexBuffer, 160);
				if (strcmp(r[i].pswd, hexBuffer) == 0){
					printf("Aproved\n");
					foundFlag = 1;
					break;
				}
			}
		}
		if (!foundFlag)
			printf("Denied\n");
	}

	if (cryptPswd != NULL)
		free(cryptPswd);
	freefArr(&r, size, 1);
	return 1;
}
